package cn.sys.service.impl;

import cn.sys.controller.dto.SearchDTO;
import cn.sys.dao.DormitoryDao;
import cn.sys.dao.ManagerInfoDao;
import cn.sys.dao.StudentDao;
import cn.sys.entity.ManagerInfo;
import cn.sys.entity.Student;
import cn.sys.service.ManagerInfoService;
import cn.sys.util.MybatisUtil;
import cn.sys.util.ResultData;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ManagerInfoServiceImpl implements ManagerInfoService {
    private SqlSession sqlSession = MybatisUtil.getSQLSession();

    /**
     * 处理登录业务逻辑，管理员没有账号冻结功能
     * @param account   账号名
     * @param password  密码
     * @return
     */
    @Override
    public ResultData login(String account, String password) {
        ManagerInfoDao managerInfoDao = sqlSession.getMapper(ManagerInfoDao.class);
        ManagerInfo managerInfo = managerInfoDao.findManagerInfoByAccountAndPass(account, password);

        if (managerInfo == null){
            return new ResultData(ResultData.LOGIN_FAIL,"登录失败",null);
        }
        return new ResultData(ResultData.LOGIN_SUCCESS,"登录成功",managerInfo);
    }

    /**
     * 处理添加一个学生信息的业务逻辑，部分未传入字段直接指定
     * @param stuName   账号名
     * @param realName  真实姓名
     * @param age   年龄
     * @param gender    性别
     * @param phoneNum  电话号码
     * @param schoolName    学校名称
     * @return
     */
    @Override
    public ResultData addStudent(String stuName, String realName, Integer age, String gender, String phoneNum, String schoolName) {
        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
        // 账号和手机号验重
        Student student1 = studentDao.findStudentByNameAndPhone(phoneNum, stuName);
        if(student1 != null){
            return ResultData.fail(ResultData.OPERATION_FAIL, "当前用户名或手机号被其他用户占用，请重试");
        }
        // 封装学生信息插入数据库
        Student student = new Student(null, stuName, "123456", realName, age, gender, phoneNum, schoolName, 0, null, null, 0);
        int i = studentDao.addStudent(student);
        if(i>0){
            return ResultData.ok(ResultData.OPERATION_SUCCESS, "添加成功");
        }
        return ResultData.fail(ResultData.OPERATION_FAIL, "添加失败，请稍后再试");
    }

    /**
     * 处理学员退寝业务逻辑，根据学生id修改住宿状态，并记录退寝时间
     * @param stuId 学生id
     * @return
     */
    @Override
    public ResultData quitDormitory(Integer stuId) {
        DormitoryDao dormitoryDao = sqlSession.getMapper(DormitoryDao.class);
        // 学生学号检测是否存在（或已经退寝）
        Integer dorId = dormitoryDao.findStuDormitoryByStuId(stuId);
        if(dorId == null){
            return ResultData.fail(ResultData.OPERATION_FAIL, "当前寝室没有该学员信息，或该学员已经退寝");
        }
        /*
            学员存在
            1. 退寝，修改状态为1，并修改时间
            2. 如果该寝室没有人了，修改寝室的状态为0（空寝）
            要先退寝再查，否则不能修改
         */
        // 修改学生住宿状态
        Date quitTime = new Date();
        int i = dormitoryDao.updateStuDormitoryState(stuId, quitTime);
        if(i>0) {
            // 根据dorId，查询该寝室是否还有人（之前写在DormitoryDao中了）
            String info = "";
            int num = dormitoryDao.findDormitoryCountByDorId(dorId);
            if (num <= 0) {   // 修改寝室状态
                int result = dormitoryDao.updateDormitoryState(dorId, 0);
                if (result > 0) {
                    info = "该寝室已被修改为空寝";
                }
            }
            // 退寝成功，需要将剩余的床位数加一
            int z = dormitoryDao.updateDormitorySurplusNum(dorId, 1);

            return ResultData.ok(ResultData.OPERATION_SUCCESS, "退寝成功！" + info);
        }
        return ResultData.fail(ResultData.OPERATION_FAIL, "操作失败，请稍后再试");
    }

    @Override
    public ResultData addStudentList(List<Map<String,Object>> students) {
        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
        // 向每条map中添加其它默认数据
        for (Map<String, Object> student : students) {
            student.put("lockState", 0);
            student.put("failCount", 0);
        }
        int i = studentDao.addStudentList(students);
        if(i>0){
            return ResultData.ok(ResultData.OPERATION_SUCCESS, "插入成功，共添加"+i +"条数据");
        }
        return ResultData.fail(ResultData.OPERATION_FAIL, "操作失败，请稍后再试");
    }

    @Override
    public ResultData findStudentList(SearchDTO searchDTO) {
        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
        // 开启分页
        PageHelper.startPage(searchDTO.getPageNum(), searchDTO.getPageSize());
        // 得到信息
        List<Map<String, Object>> info = studentDao.findStudentAndDormitoryAndPosition(searchDTO);
        // 得到分页信息
        PageInfo pageInfo = PageInfo.of(info);

        ResultData resultData = new ResultData();
        resultData.put("result",true);
        resultData.put("msg", "");
        Map<String, Object> pageMap = new HashMap<>();
        pageMap.put("currPage", searchDTO.getPageNum());
        pageMap.put("total", pageInfo.getTotal());
        pageMap.put("pageSize", searchDTO.getPageSize());
        resultData.put("pagination", pageMap);
        resultData.put("datas", info);
        return resultData;
    }

    @Override
    public ResultData findStudentByStuIdAndPhoneNum(SearchDTO searchDTO) {
        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
        // 得到信息
        Student student = studentDao.findStudentByStuIdAndPhoneNum(searchDTO.getStuId(), searchDTO.getPhoneNum());
        if(student == null){
            return ResultData.fail(ResultData.OPERATION_FAIL, "没有学生信息");
        }
        return new ResultData(ResultData.OPERATION_SUCCESS, "查询成功", student);
    }

    /**
     * 学员账号解锁业务处理
     * 修改锁定状态、失败的登录次数、重置密码
     * @param stuId
     * @return
     */
    @Override
    public ResultData dealLockedState(Integer stuId) {
        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
        int i = studentDao.updateStudentLockStateAndFailCountAndPassword(stuId);
        if(i>0){
            return ResultData.ok(ResultData.OPERATION_SUCCESS, "修改成功");
        }
        return ResultData.fail(ResultData.OPERATION_FAIL, "修改失败，请稍后再试");
    }
}
